﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using FinPlusCommon;
using Messaging2;
using log = Logger.Logger;

namespace FinPlusComponents
{
    public class FinPlusMessaging: FinPlusComponent
    {
        public event EventHandler<IFunction> OnUpdate;

        private readonly ITransport _tran; 

        //construct
        public FinPlusMessaging(string address, int port, string topic = null)
        {
            if(_tran == null) _tran = new Transport(address, port);
            
            _tran.Listener.MessageRecieved += MessageEvent;
            
            if (!string.IsNullOrEmpty(topic)) Listen(topic);

            IsValid = true;
        }

        //common control interface
        public override void CmdExecute(IFunction command)
        {
            try
            {
                CmdCapture(command);
                Update(command);
            }
            catch (CmdExecuteException e)
            {
                IsValid = log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }
        }

        public override void Dispose()
        {
            try
            {
                _tran.Dispose();
            }
            catch (Exception e)
            {
                log.Log(Logger.Level.Warning, e.Message, e);
            }
        }

        //public
        public void Listen(string topic)
        {
            if (_tran != null) _tran.Listen(topic);
        }

        public void Publish(IMessage message)
        {
            if (_tran != null) _tran.Publish(message);
        }

        //private 
        private void Update(IFunction func)
        {
            if (OnUpdate != null)
                OnUpdate(this, func);
        }

        //cmds
        private enum Cmds { Update }

        //events 
        private void MessageEvent(object s, EventArgs a)
        {
            CmdExecute(new Function(((MessageEventArgs)a).Message));
        }
    }
}
